"use strict";
/**
 * 发送普通模板消息服务
 * Created by liamjung on 2018/6/28.
 */
const {ResponseError} = require("@libfintech/api-gateway-core/error/response_error");
const {getMsg} = require("@libfintech/api-gateway-core/util/template_util");
const AbstractService = require("../abstract_service");

class MsgTempService extends AbstractService {

    /**
     * 执行
     * @param dto       MsgTempDTO
     * @param mpConfig  公众号配置
     * @param pipeline  管道
     * @returns {Promise.<void>}
     */
    async execute(dto, mpConfig, pipeline) {

        let msgTempPath = super.getMsgTempPath(mpConfig, dto.type);

        if (dto.data) {
            for (let d of dto.data) {
                if (d.value.startsWith("http://") || d.value.startsWith("https://"))
                    d.value = this.oauth2buildAuthorizationUrl(d.value, "snsapi_base", "STATE");
            }
        }

        let content = getMsg(msgTempPath, dto.data);

        if (!content) {
            //消息不存在时，抛出异常
            throw new ResponseError(404, undefined, "普通模板不存在")
        }

        let bodyJson = {
            touser: dto.openId,
            msgtype: "text",
            text: {
                content: content
            }
        };

        super.updateRequest(pipeline.request, undefined, bodyJson);
    }
}

module.exports = new MsgTempService();